package com.dapeis.web.wx.controller.impl;

import java.io.IOException;
import java.util.Date;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.ag.utils.NumberUtils;
import com.dapeis.core.utils.StylistConstants;
import com.dapeis.domain.Order;
import com.dapeis.domain.Plan;
import com.dapeis.pay.swiftpass.config.SPPayConfig;
import com.dapeis.pay.swiftpass.util.SPPayUtil;
import com.dapeis.pay.swiftpass.util.SignUtils;
import com.dapeis.pay.swiftpass.util.XmlUtils;
import com.dapeis.service.CollocationPlanService;
import com.dapeis.service.MoneyLogService;
import com.dapeis.service.OrderService;
import com.dapeis.service.RequirementService;
import com.dapeis.service.TIMService;
import com.dapeis.web.wx.controller.RestController;

/**
 * swfitpass 威富通支付接收通知接口 Title:SPNotifyController.java SPNotifyController
 * Description:
 * 
 * @author yuanyong
 * @date 2017年5月3日 下午4:16:09 Email: hzyuanyong@126.com
 *
 */
@Controller
@RequestMapping("/wx/sppay")
public class SPNotifyController extends RestController {

    final Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    OrderService orderService;
    @Resource
    CollocationPlanService planService;
    @Resource
    MoneyLogService moneyLogService;
    @Resource
    RequirementService requirementService;
    @Resource
    TIMService timService;

    @RequestMapping(value = "/notify", method = RequestMethod.POST)
    public void notify(HttpServletRequest request, HttpServletResponse response)
	    throws IOException {
	String respString = "error";
	try {
	    logger.info("收到SP发来的消息.....");
	    response.setCharacterEncoding(SPPayConfig.charset);
	    response.setCharacterEncoding(SPPayConfig.charset);
	    response.setHeader("Content-type",
		    StylistConstants.ContentType.TEXT_HTML);
	    String resString = XmlUtils.parseRequst(request);
	    if (resString != null && !"".equals(resString)) {
		Map<String, String> map = XmlUtils.toMap(resString.getBytes(),
			SPPayConfig.charset);
		String res = XmlUtils.toXml(map);
		if (map.containsKey("sign")) {
		    if (!SignUtils.checkParam(map, SPPayConfig.key)) {
			res = "验证签名不通过";
			respString = "error";
		    } else {
			if (SPPayUtil.checkPayResult(map)) {// 支付成功
			    // 获取订单号：
			    String out_trand_no = map.get(
				    SPPayUtil.PROPERTY_OUT_TRADE_NO).toString();
			    Long orderId = new Long(out_trand_no);
			    Order order = orderService.selectForLock(orderId);
			    String total_fee = map.get(
				    SPPayUtil.PROPERTY_PAY_TOTAL_FEE)
				    .toString();
			    if (null != order
				    && order.getTransactionPrice().toString()
					    .equals(total_fee)) {
				if (order.getPayState() == StylistConstants.Order.PayStatus.WAIT_PAY) {
				    order.setPayState(StylistConstants.Order.PayStatus.PAY_SUCCESS);
				    order.setPayTime(new Date().getTime() / 1000);

				    if (requirementService
					    .isShopRequirement(order)) {
					// 选择搭配师服务
					order.setState(StylistConstants.Order.Status.SERVICE);
					order.setTaskTime(new Date().getTime() / 1000);
					//收支明细
					orderService
						.updateByPrimaryKeySelective(order);
					moneyLogService.task(order);
					timService.addFriend(
						order.getCollocationId(),
						order.getUserId());
				    } else {
					order.setState(StylistConstants.Order.Status.PAY_SUCCESS);
					orderService
						.updateByPrimaryKeySelective(order);
				    }

				    if (order
					    .getType()
					    .equals(StylistConstants.Order.Type.AWARD_PROGRAM)) {
					// 方案打赏
					Plan plan = planService
						.selectByPrimaryKey(order
							.getLinkId());
					if (null != plan) {
					    plan.setAwardNum(plan.getAwardNum()
						    + order.getOriginalPrice());
					    planService
						    .updateByPrimaryKeySelective(plan);
					    // 更新收支明细
					    moneyLogService.award(order, plan);
					    logger.info("SP通知 更新搭配方案金额{}",
						    order.getOriginalPrice());
					}
				    }
				    logger.info("SP通知，订单:{}状态更新成功,已经支付了..",
					    order.getId());
				}
				respString = "success";
			    } else {
				logger.info("SP 通知,订单不存在 orderId:{}", orderId);
			    }
			    logger.info("SP 通知,支付失败code:{},详情{}",
				    SPPayUtil.getCode(map),
				    SPPayUtil.getResultMsg(map));
			}
		    }
		}
	    }
	} catch (Exception e) {
	    logger.error("操作失败，原因：", e);
	} finally {
	    response.getWriter().write(respString);
	}

    }
}
